﻿import type {RequestOptions} from '@@/plugin-request/request';
import {RequestConfig} from '@umijs/max';

// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  errorCode?: number;
  errorMessage?: string;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const requestConfig: RequestConfig = {
  baseURL: getURL(),
  withCredentials: true,
  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      config.headers = {
        ...config.headers,
        'Access-Control-Allow-Origin': '*', // 设置允许所有来源, 但主要依赖于后端
      };
      // 拦截请求配置，进行个性化处理。
      // const url = config?.url?.concat('?token = 123');
      // return {...config, url};
      return config;
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const contentType = response.headers['content-type'];
      if (contentType?.includes('application/octet-stream')) {
        return response;
      }

      // 对于其他响应类型，进行常规处理
      const {data} = response as unknown as ResponseStructure;
      console.log('data', data);
      if (data.code !== 0) {
        throw new Error(data.message);
      }
      return response;
    },
  ],
};

function getURL() {
  const env = REACT_APP_ENV;
  console.log('REACT_APP_ENV', env)
  switch (env) {
    case 'test':
      return 'http://localhost:8000/api';
    case 'dev':
      return 'http://localhost:8000/api';
    case 'prod':
      return 'http://localhost:7529/api';
    default:
      return 'http://localhost:7529/api';
  }
}
